package com.xjc.system.interceptor;

import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xjc.business.entity.po.stu.MatchFacePo;
import com.xjc.business.service.SchoolSetsService;
import com.xjc.system.constants.MyConstants;
import com.xjc.system.result.Result;
import com.xjc.system.result.ResultCode;
import com.xjc.system.utils.SpringBeanContext;
import com.xjc.system.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 徐锦程
 * 时间:2024-10-01 16:01
 * 描述:token拦截器
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {


    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String token = request.getHeader("token");

        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.setStatus(ResultCode.SUCCESS.getCode());

        // 校验Token是否有效
        if (token == null || !TokenUtils.isTokenValid(token)) {
            try {
                // 无效-返回错误信息
                Result errorResponse = Result.builder().code(ResultCode.UNAUTHORIZED.getCode()).message(ResultCode.UNAUTHORIZED.getMessage()).build();
                response.getWriter().write(objectToJson(errorResponse));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }else{
            String role = request.getHeader("role");
            if(role!=null){
                try {
                    SchoolSetsService schoolSetsService = SpringBeanContext.getContext().getBean(SchoolSetsService.class);
                    String subject = TokenUtils.parseToken(token).getSubject();
                    // 有效-验证所属学校服务是否过期
                    if (!schoolSetsService.sureHasSet(role, Integer.valueOf(subject))) {
                        Result errorResponse = Result.builder().code(ResultCode.NOTOPEANSET.getCode()).message(ResultCode.NOTOPEANSET.getMessage()).build();
                        response.getWriter().write(objectToJson(errorResponse));
                        return false;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        }

        return true;
    }

    /**
     * 将对象转换为JSON字符串
     */
    private String objectToJson(Object obj) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(obj);
    }
    
}
